const cp = require('child_process')
const util = require('util')
// const exec = util.promisify(cp.exec)
const path = require('path')
const env = process.env
const { Command } = require('commander')
const program = new Command()
const archiver = require('archiver')
const fs = require('fs')
const rm = util.promisify(require('rimraf'))
const {
  resolve,
  log,
  successLog,
  errorLog,
  showLoading,
  hideLoading,
  getHirtime,
} = require('../utils.js')
const exec = require('shelljs').exec //|| util.promisify(require('shelljs').exec);
/**
 * zip file
 *   sourceFile，待压缩的文件
 *   destZip，压缩后的zip文件
 *   cb，callback
 */
function zipFile(sourceFile, destZip, level = 9) {
  return new Promise((resolve, reject) => {
    // init
    var output = fs.createWriteStream(destZip)
    var archive = archiver('zip', {
      zlib: { level: level },
    })
    // on
    output.on('close', function () {
      console.log('zip file success!')
      resolve('zip file success!')
    })
    archive.on('error', function (err) {
      console.log('zip file error!>>>', err)
      reject(err)
    })
    // zip
    archive.pipe(output)
    archive.file(sourceFile, {
      name: path.basename(sourceFile),
    })
    archive.finalize()
  })
}

/**
 * zip folder
 *   sourceFolder，待压缩的文件夹
 *   destZip，压缩后的zip文件
 *   subdir，是否需要包一层
 */
function zipFolder(sourceFolder, destZip, subdir = true, level = 9) {
  return new Promise((resolve, reject) => {
    // init
    var output = fs.createWriteStream(destZip)
    var archive = archiver('zip', {
      zlib: { level: level },
    })

    // on
    output.on('close', function () {
      resolve(null, 'zip folder success!')
    })
    archive.on('error', function (err) {
      reject(err)
    })

    // zip
    archive.pipe(output)
    //sourceFolder.substr(path.dirname(sourceFolder).length + 1)
    archive.directory(sourceFolder, subdir ? sourceFolder : false)
    archive.finalize()
  })
}

//导出函数
module.exports = async (options) => {
  async function commpressFn(options) {
    //压缩zip
    let { zip, folder, level, subdir } = options
    folder = folder ? folder : 'dist'
    zip = zip ? zip : 'dist.zip'
    console.log('options>>>>', options)
    showLoading()
    try {
      //删除本地已存在的zip文件
      console.log('delete zip file')
      await rm(zip)
      console.log('delete sucess!')
      console.log('start autoCompress!')
      await zipFolder(folder, zip, level, subdir ? true : false)
      console.log('end autoCompress!')
    } catch (error) {}
    hideLoading()
    getHirtime()
  }
  commpressFn(options)
}
